package com.gx.util.fileutil;

import lombok.Data;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by gx on 2017/5/25.
 */
@Data
public class FTPUtil {
    private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);

    private static String ftpIp = PropertiesUtil.getPropertyKey("ftp.server.ip");
    private static String ftpUser = PropertiesUtil.getPropertyKey("ftp.user");
    private static String ftpPass = PropertiesUtil.getPropertyKey("ftp.pass");
    private String ip;
    private int port;
    private String user;
    private String pwd;
    private FTPClient ftpClient;

    public FTPUtil(String ip, int port, String user, String pwd) {
        this.ip = ip;
        this.port = port;
        this.user = user;
        this.pwd = pwd;
    }

    public static boolean uploadFile(List<File> fileList) throws IOException {
        FTPUtil ftpUtil = new FTPUtil(ftpIp, 21, ftpUser, ftpPass);
        logger.info("开始连接ftp服务器");
        boolean result = ftpUtil.uploadFile("img", fileList);
        logger.info("开始连接ftp服务器,结束上传,上传结果:{}");
        return result;
    }

    private boolean uploadFile(String remotePath, List<File> fileList) throws IOException {
        boolean uploaded = true;
        FileInputStream fis = null;
        //连接FTP服务器
        if (connectServer(this.ip, this.port, this.user, this.pwd)) {
            try {
                ftpClient.changeWorkingDirectory(remotePath);//设置远程路径
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");//设置编码
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//设置2进制 文件 防止乱码
                ftpClient.enterLocalPassiveMode();//打开被动模式
                for (File fileItem : fileList) {
                    fis = new FileInputStream(fileItem);
//                                        文件名            文件
                    ftpClient.storeFile(fileItem.getName(), fis);//上传
                }
            } catch (IOException e) {
                logger.error("上传文件异常", e);
                uploaded = false;
                e.printStackTrace();
            } finally {
                fis.close();
                ftpClient.disconnect();//关闭连接
            }
        }
        return uploaded;
    }

    /**
     * 连接FRP
     *
     * @param ip
     * @param port
     * @param user
     * @param pwd
     * @return
     */
    private boolean connectServer(String ip, int port, String user, String pwd) {
        boolean isSuccess = false;
        this.ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip, port);
            isSuccess = ftpClient.login(user, pwd);
        } catch (IOException e) {
            logger.error("连接FTP服务器异常", e);
        }
        return isSuccess;
    }




}
